package com.vr.xuecheng.learning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vr.xuecheng.base.exception.XueChengPlusException;
import com.vr.xuecheng.common.util.SecurityUtils;
import com.vr.xuecheng.feign.client.CoursePublishClient;
import com.vr.xuecheng.feign.dto.CoursePublishDTO;
import com.vr.xuecheng.learning.dto.CourseTablesDTO;
import com.vr.xuecheng.learning.entity.ChooseCourse;
import com.vr.xuecheng.learning.entity.CourseTables;
import com.vr.xuecheng.learning.mapper.ChooseCourseMapper;
import com.vr.xuecheng.learning.service.IChooseCourseService;
import com.vr.xuecheng.learning.service.ICourseTablesService;
import com.vr.xuecheng.learning.vo.ChooseCourseVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzh
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class ChooseCourseServiceImpl extends ServiceImpl<ChooseCourseMapper, ChooseCourse> implements IChooseCourseService {
    private final ChooseCourseMapper chooseCourseMapper;
    private final CoursePublishClient coursePublishClient;
    private final ICourseTablesService courseTablesService;
    @Autowired
    @Lazy
    private  IChooseCourseService chooseCourseService;

    @Override
    public ChooseCourseVO chooseCourse(Long courseId) throws XueChengPlusException {
        // 获取当前登录的用户信息
        SecurityUtils.User user = SecurityUtils.getUser();
        if (user == null) {
            XueChengPlusException.cast("用户未登录,无法选择课程");
        }
        String userId = user.getId();
        // 远程调用查询所选课程信息
        CoursePublishDTO coursePublishDTO = coursePublishClient.getCoursePublishInfoById(courseId);
        if (coursePublishDTO == null) {
            XueChengPlusException.cast("选择课程失败，课程未发布，或不存在");
        }
        ChooseCourse chooseCourse;
        String charge = coursePublishDTO.getCharge();
        if ("201000".equals(charge)) {
            // 课程免费
            // 添加免费课程
            chooseCourse = chooseCourseService.addFreeCourse(String.valueOf(userId), coursePublishDTO);
            // 添加我的课程表
            CourseTables courseTables = courseTablesService.addCourseTabls(chooseCourse);
        } else {
            // 课程收费
            chooseCourse = chooseCourseService.addChargeCourse(String.valueOf(userId), coursePublishDTO);
        }
        ChooseCourseVO chooseCourseVO = BeanUtil.toBean(chooseCourse, ChooseCourseVO.class);
        // 获取学习资格
        CourseTablesDTO courseTablesDTO = chooseCourseService.getLearningStatus(String.valueOf(userId), courseId);
        chooseCourseVO.setLearnStatus(courseTablesDTO.getLearnStatus());
        return chooseCourseVO;
    }

    @Override
    public ChooseCourse addFreeCourse(String userId, CoursePublishDTO coursePublishDTO) {
        // 判断一下当前用户是否已经选过
        List<ChooseCourse> result = chooseCourseMapper.selectList(new LambdaQueryWrapper<ChooseCourse>()
                .eq(ChooseCourse::getCourseId, coursePublishDTO.getId())
                // 选课完成状态
                .eq(ChooseCourse::getStatus, "701001")
                .eq(ChooseCourse::getUserId, userId)
        );
        if (result != null && !result.isEmpty()) {
            log.error("用户已经选过该课程");
            return result.get(0);
        }
        // 构建数据
        long freeValidDays = 365;
        float freeCoursePrice=0F;
        LocalDateTime endTime = LocalDateTime.now().plusDays(freeValidDays);
        ChooseCourse chooseCourse = ChooseCourse.builder()
                .courseId(coursePublishDTO.getId())
                .courseName(coursePublishDTO.getName())
                .userId(userId)
                .companyId(coursePublishDTO.getCompanyId())
                // 免费课程
                .orderType("700001")
                .coursePrice(freeCoursePrice)
                .validDays((int) freeValidDays)
                // 选课成功
                .status("701001")
                .validtimeStart(LocalDateTime.now())
                .validtimeEnd(endTime)
                .remarks(coursePublishDTO.getRemark())
                .build();
        chooseCourseMapper.insert(chooseCourse);
        return chooseCourse;
    }

    @Override
    public ChooseCourse addChargeCourse(String userId, CoursePublishDTO coursePublishDTO) {
        // 判断一下当前用户是否已经选过
        List<ChooseCourse> result = chooseCourseMapper.selectList(new LambdaQueryWrapper<ChooseCourse>()
                .eq(ChooseCourse::getCourseId, coursePublishDTO.getId())
                // 选课待支付状态,为已支付
                .eq(ChooseCourse::getStatus, "701002")
                .eq(ChooseCourse::getUserId, userId)
        );
        if (result != null && !result.isEmpty()) {
            return result.get(0);
        }
        LocalDateTime endTime = LocalDateTime.now().plusDays(coursePublishDTO.getValidDays());
        // 构建数据
        ChooseCourse chooseCourse = ChooseCourse.builder()
                .courseId(coursePublishDTO.getId())
                .courseName(coursePublishDTO.getName())
                .userId(userId)
                .companyId(coursePublishDTO.getCompanyId())
                // 免费课程
                .orderType("700002")
                .coursePrice(coursePublishDTO.getPrice())
                .validDays(coursePublishDTO.getValidDays())
                // 选课成功
                .status("701002")
                .validtimeStart(LocalDateTime.now())
                .validtimeEnd(endTime)
                .remarks(coursePublishDTO.getRemark())
                .build();
        chooseCourseMapper.insert(chooseCourse);
        return chooseCourse;
    }

    @Override
    public CourseTablesDTO getLearningStatus(String userId, Long courseId) {
        CourseTables courseTables = courseTablesService.getOne(new LambdaQueryWrapper<CourseTables>()
                .eq(CourseTables::getUserId, userId)
                .eq(CourseTables::getCourseId, courseId)
        );
        CourseTablesDTO courseTablesDTO = new CourseTablesDTO();
        if (courseTables == null) {
            // 表示未选课或者未支付
            courseTablesDTO.setLearnStatus("702002");
            return courseTablesDTO;
        }
        BeanUtil.copyProperties(courseTables, courseTablesDTO);
        boolean isExpired = courseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if (isExpired) {
            // 表示选课存在，但过期了
            courseTablesDTO.setLearnStatus("702003");
        }
        // 存在且未过期，正常学习
        courseTablesDTO.setLearnStatus("702001");
        return courseTablesDTO;
    }

    @Override
    public boolean updateChooseCourseSuccess(Long courseId) {
        // 查询课程
        ChooseCourse chooseCourse = chooseCourseService.getById(courseId);
        if (chooseCourse == null) {
            log.debug("收到支付结果通知没有查询到关联的选课记录,courseId:{}",courseId);
            return false;
        }
        String status = chooseCourse.getStatus();
        if ("701001".equals(status)) {
            // 表示已经选课成功了，直接添加到我的课程里
            courseTablesService.addCourseTabls(chooseCourse);
            return true;
        }
        if ("701002".equals(status)) {
            // 待支付状态变成选课成功
            chooseCourse.setStatus("701001");
            boolean f = chooseCourseService.updateById(chooseCourse);
            if (!f) {
                // 处理选课失败
                log.error("收到支付结果通知处理失败,选课记录:{}", chooseCourse);
                return false;
            }
            log.debug("收到支付结果通知处理成功,选课记录:{}", chooseCourse);
            courseTablesService.addCourseTabls(chooseCourse);
            return true;
        }
        return false;
    }
}
